-- =======================================================
-- ==                Background Runner                  ==
-- =======================================================
-- Runs a specified Lua script in a new, detached thread.
-- Usage: bg /path/to/script.lua
-- =======================================================

local thread = require("thread")

-- The '...' expression captures all command-line arguments passed to the script.
local args = {...}
local file_to_run = args[1]

-- Step 1: Validate input
-- Check if the user provided a filename.
if not file_to_run then
print("Error: No script specified.")
print("Usage: bg <path_to_script>")
return -- Exit if no file is given
end

-- Step 2: Create the thread
-- We wrap the core logic in a pcall to catch potential errors during thread creation itself.
local ok, new_thread = pcall(thread.create, function()
-- Inside the new thread, we use another pcall to run the user's script.
-- This is crucial: it prevents an error in the background script from
-- crashing the entire computer. The error will only terminate this thread.
local success, err = pcall(dofile, file_to_run)
if not success then
-- If the background script fails, print the error to the console.
-- This is very helpful for debugging.
print("Error in background script '" .. file_to_run .. "':")
print(tostring(err))
end
end)

if not ok then
print("Error: Failed to create a new thread.")
print(tostring(new_thread)) -- Print the error message from pcall
return
end

-- Step 3: Detach the thread
-- This allows the thread to continue running even after the 'bg.lua' script itself finishes.
new_thread:detach()

-- Step 4: Give user feedback
print("Launched '" .. file_to_run .. "' in the background.")